const AuditLogModel = require('../models/auditLogModel')
const { getDbPool } = require('../infra/dbClient')
const db = getDbPool()
const { getClientIP, parseUserAgent, getLocationByIP } = require('./utils')


// 数据脱敏
const redact = (obj) => {
    if (!obj) return null
    const cloned = JSON.parse(JSON.stringify(obj))
    const keys = ['password', 'oldPassword', 'newPassword', 'token']
    keys.forEach(k => { if (cloned && cloned[k] !== undefined) cloned[k] = '***' })
    return cloned
}

// referer 处理转化
const convertReferer = (referer) => {
    if (!referer) return null;

    let host = referer.split('//')[1];
    // 去除参数
    let queryindex = host.indexOf('?');
    if (queryindex !== -1) {
        host = host.substring(0, queryindex);
    }
    // 去除前缀
    let pathindex = host.indexOf('/');
    if (pathindex !== -1) {
        host = host.substring(pathindex, host.length);
    }
    return host
}



// 记录审计日志
const logAudit = async (req, payload = {}) => {

    let userId = req.user?.id || null
    let username = req.user?.username || ''

    if (payload.business_type === 'login') {
        userId = payload.target_entity_id || null;
        username = payload.target_entity_name || '';
    }


    let deptId = null
    let deptName = null
    if (userId) {
        const [rows] = await db.execute('SELECT u.department_id as dept_id, d.name as dept_name FROM user u LEFT JOIN department d ON u.department_id = d.id WHERE u.id = ? AND u.is_delete = 0', [userId])
        const row = rows[0] || {}
        deptId = row.dept_id || null
        deptName = row.dept_name || null
    }
    const ip = getClientIP(req)
    const location = getLocationByIP(ip) || '未知'
    const ua = req.headers['user-agent'] || ''
    const uaInfo = parseUserAgent(ua)
    const referer = (req.get && req.get('Referer')) || req.headers['referer'] || null
    const clientPage = req.headers['x-client-page'] || null
    const data = {
        user_id: userId,
        username,
        dept_id: deptId,
        dept_name: deptName,
        action_type: payload.action_type || '',
        module_code: payload.module_code || '',
        business_type: payload.business_type || null,
        operation_desc: payload.operation_desc || null,
        url: req.originalUrl || req.url || '',
        method: req.method || '',
        data_type: payload.data_type || 1,
        target_dept_id: payload.target_dept_id || null,
        target_dept_name: payload.target_dept_name || null,
        target_entity_type: payload.target_entity_type || null,
        target_entity_id: payload.target_entity_id || null,
        target_entity_name: payload.target_entity_name || null,
        client_ip: ip,
        location,
        user_agent: ua,
        browser: uaInfo.browser,
        operating_system: uaInfo.operatingSystem,
        referer: convertReferer(referer),
        device_type: uaInfo.deviceType,
        before_data: redact(payload.before_data) || null,
        after_data: redact(payload.after_data) || null,
        change_summary: (() => {
            const base = payload.change_summary || null
            const source = clientPage ? `source_page: ${clientPage}` : (referer ? `referer: ${referer}` : null)
            if (!source) return base
            if (!base) return source
            return `${base} | ${source}`
        })()
    }
    return AuditLogModel.create(data)
}

module.exports = { logAudit }